<!-- 项目合同 -->
<template>
  <div>
    <!-- <s-table
      ref="table"
      :columns="$auth('PROJECT.PROJECT_AGREEMENT_LIST') ? columns : []"
      bordered
      :data="loadData"
      :pagination="false"
      :rowKey="record => record.id"
    >
      <template slot="title">
        <a-descriptions title="项目合同"></a-descriptions>
        <div class="table-page-search-wrappers">
          <a-form layout="inline">
            <a-row :gutter="48">
              <a-col :md="6" :sm="24">
                <a-form-item label="当前状态">
                  <a-select v-model="queryParam.status" allowClear>
                    <a-select-option v-for="item in $const.SIGNING_STATUS" :value="item.value" :key="item.value">
                      {{ item.desc }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="签署人">
                  <a-select v-model="queryParam.signUserNo" allowClear>
                    <a-select-option v-for="(item, index) in showUserNoList" :value="item.userNo" :key="index">
                      {{ item.userName }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="合同类型">
                  <a-select v-model="queryParam.signType" allowClear>
                    <a-select-option v-for="(item, index) in selectSignType" :value="item.value" :key="index">
                      {{ item.desc }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="4" :sm="24">
                <span class="table-page-search-submitButtons">
                  <a-button type="primary" @click="activeQuery">查询</a-button>
                  <a-button style="margin-left: 8px;" @click="activeQuery('reset')">重置</a-button>
                  <a-button
                    v-if="$auth('PROJECT.PROJECT_AGREEMENT_IMPORT')"
                    style="margin-left: 8px"
                    icon="export"
                    @click="clickExport"
                  >导出</a-button>
                </span>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </template>

      <template slot="id" slot-scope="text, record, index">
        {{ index | getPageIndex($refs.table) }}
      </template>
      <template slot="signType" slot-scope="text, record">
        <span v-if="record.signType == 1"> 电子签 </span>
        <span v-if="record.signType == 2"> 上传签属文件 </span>
      </template>
      <template slot="signTime" slot-scope="text, record">
        <span v-if="record.signTime">{{ record.signTime | moment() }}</span>
        <span v-else>——</span>
      </template>
      <template slot="status" slot-scope="text, record">
        {{ record.status | enumValueByKey($const.SIGNING_STATUS) }}
      </template>
      <template slot="fileUrl" slot-scope="text, record">
        <a
          target="_blank"
          v-if="(Number(record.status) === 3 || Number(record.status) === 4) && $auth('PROJECT.PROJECT_AGREEMENT_DETAIL') && !projectClosed"
          @click="viewFile(record)"
        >查看
        </a>
        <a
          target="_blank"
          v-if="[1, 2].includes(+record.status) && !projectClosed"
          @click="cancelContract(record)"
        >取消
        </a>
      </template>
    </s-table> -->
    <!-- <a-button
      type="primary"
      v-if="$auth('PROJECT.PROJECT_AGREEMENT_ADD')"
      @click="initiate"
      style="margin: 20px 0;"
      :disabled="$store.state.user.project.status === 3"
    >
      发起合同
    </a-button> -->
    <!-- ====== 合同模版 ====== -->
    <s-table
      ref="tables"
      :columns="columnsTwo"
      bordered
      :data="templatesList"
      :pagination="false"
    >
      <template slot="title">
        <a-descriptions :title="$t('all.autotext1309')"></a-descriptions>
        <div class="table-page-search-wrappers"></div>
      </template>
      <template slot="id" slot-scope="text, record, index">
        {{ index | getPageIndex($refs.tables) }}
      </template>
      <template slot="url" slot-scope="text, record" v-if="$store.state.user.project.status !== 3">
        <a @click="clickViewFile(record.url)" style="margin-right: 10px;">{{ $t('all.autotext568') }}</a>
        <template v-if="editable">
          <!-- status 1 启用中 2 已停用 -->
          <a @click="switchState(record, 1)" style="margin-right: 10px;" v-if="record.status == 0 ">{{ $t('all.autotext307') }}</a>
          <a @click="switchState(record, 0)" style="margin-right: 10px;" v-if="record.status == 1 ">{{ $t('all.autotext764') }}</a>
          <a @click="visibleDeploySwitch(record)" >{{ $t('all.autotext1145') }}</a>
        </template>
      </template>
      <template slot="status" slot-scope="text, record">
        <span v-if="record.status == 0">{{ $t('all.autotext764') }}</span>
        <span v-if="record.status == 1">{{ $t('all.autotext307') }}</span>
      </template>
      <template slot="createTime" slot-scope="text, record">
        <span>{{ record.createTime | moment() }}</span>
      </template>
      <template slot="signedLaunch" slot-scope="text, record">
        <span>{{ record.initiate }}/{{ record.signedShare }} </span>
      </template>
    </s-table>
    <a-button
      type="primary"
      @click="upload"
      style="margin: 20px 0;"
      :disabled="$store.state.user.project.status === 3"
      v-if="editable"
    >
      {{ $t('all.autotext101') }}
    </a-button>
    <!-- 弹出层组件 -->
    <ContractDisplay
      :visible="visible"
      @modalOk="addSubmit"
      @modalCancel="addCancel"
      ref="ContractDisplay"
    ></ContractDisplay>
    <!-- 配置弹出层 -->
    <Allocation
      :visible="visibleDeploy"
      @AllocationOk="AllocationOk"
      @AllocationCancel="AllocationCancel"
      ref="Allocation"
      :defaultData="currentTemplateRow"
    ></Allocation>
    <!-- 提交弹出层 -->
    <UploadContract
      :visible="visibleUpload"
      @uploadModalCancel="uploadModalCancel"
      @uploadClickConfirm="uploadClickConfirm"
      ref="UploadContract"
    ></UploadContract>
    <!-- 查看文件弹出层 -->
    <ViewFile ref="viewFileRef" :viewFileVisible="viewFileVisible" @closeViewFile="closeViewFile" />
    <TextAreaModal
      ref="TextAreaModal"
      :visible="TextAreaVisible"
      :config="pdfConfig"
      @handleCancel="handleTextAreaCancel"
      @handleSuccess="handleTextAreaSuccess"
    />
    <!-- 查看合同模板 -->
    <a-modal
      width="80%"
      :visible="modalVisible"
      :footer="null"
      @cancel="modalVisible = false"
    >
      <div class="pdf">
        <pdf
          ref="pdf"
          v-for="i in numPages"
          :key="i"
          :src="fileUrl"
          :page="i"
        ></pdf>
      </div>
    </a-modal>
    <!-- 预览pdf合同 -->
    <pdfPreview :visible="pdfVisible" :url="fileUrl" @handleCancel="pdfVisible = false" />
  </div>
</template>

<script>
import pdf from 'vue-pdf-sign'
// 预览pdf用下面这个
import pdfPreview from '@/components/pdfPreview/index.vue'

import {
  // list,
  getTemplateList,
  switchUpdateCon,
  getAddContract,
  contractConfig,
  getAddCon,
  // showUserNo,
  exportContract,
  apiCancelContract
} from '@/api/project/configItem/contract'
import ContractDisplay from './ContractDisplay'
import Allocation from './allocation'
import UploadContract from './UploadContract'
import ViewFile from './contract/ViewFile'
import { exportExcel } from '@/utils/util'
// import { buildPaginationObj } from '@/components/Table'
import TextAreaModal from './textAreaModal'
import { mapGetters } from 'vuex'

export default {
  name: '',
  props: {
    editable: {
      type: Boolean,
      default: false
    }
  },
  components: {
    ContractDisplay,
    Allocation,
    UploadContract,
    ViewFile,
    TextAreaModal,
    pdf,
    pdfPreview
  },
  data () {
    const columns = [
      {
        title: this.$t('all.autotext334'),
        dataIndex: 'id',
        scopedSlots: { customRender: 'id' }
      },
      {
        title: this.$t('all.autotext1407'),
        dataIndex: 'signType',
        scopedSlots: { customRender: 'signType' }
      },
      {
        title: this.$t('all.autotext630'),
        dataIndex: 'fileName'
      },
      {
        title: this.$t('all.autotext768'),
        dataIndex: 'account'
      },
      {
        title: this.$t('all.autotext1480'),
        dataIndex: 'signTime',
        scopedSlots: { customRender: 'signTime' }
      },
      {
        title: this.$t('all.autotext175'),
        dataIndex: 'status',
        scopedSlots: { customRender: 'status' }
      },
      {
        title: this.$t('all.autotext187'),
        dataIndex: 'fileUrl',
        scopedSlots: { customRender: 'fileUrl' }
      }
    ]
    const columnsTwo = [
      {
        title: this.$t('all.autotext334'),
        dataIndex: 'id',
        scopedSlots: { customRender: 'id' }
      },
      {
        title: this.$t('all.autotext630'),
        dataIndex: 'name'
      },
      {
        title: this.$t('all.autotext1116'),
        dataIndex: 'createTime',
        scopedSlots: { customRender: 'createTime' }
      },
      {
        title: this.$t('all.autotext1466'),
        dataIndex: 'status',
        scopedSlots: { customRender: 'status' }
      },
      // {
      //   title: '签署/发起',
      //   dataIndex: 'signedLaunch',
      //   scopedSlots: { customRender: 'signedLaunch' }
      // },
      {
        title: this.$t('all.autotext187'),
        dataIndex: 'url',
        scopedSlots: { customRender: 'url' }
      }
    ]
    return {
      configId: '',
      viewFileVisible: false,
      columns,
      columnsTwo,
      contractId: '',
      visible: false, // 弹出层显示状态
      visibleDeploy: false, // 配置弹出层状态
      visibleUpload: false, // 提交弹出层
      currentTemplateRow: {}, // 当前选中的合同模板
      queryParam: {
        proId: ''
      },
      // loadData: (parameter) => {
      //   return list(Object.assign(parameter, { ...this.queryParam, configId: this.configId })).then((res) => {
      //     return res
      //   })
      // },
      // // 合同模版
      templatesList: (parameter) => {
        return getTemplateList(Object.assign(parameter, { proId: this.queryParam.proId, configId: this.configId })).then((res) => {
          return res
        })
      },
      selectMap: [
        {
          value: 1,
          desc: this.$t('all.autotext204')
        },
        {
          value: 2,
          desc: this.$t('all.autotext1363')
        }
      ],
      selectSignType: [
        {
          value: 1,
          desc: this.$t('all.autotext359')
        },
        {
          value: 2,
          desc: this.$t('all.autotext1037')
        }
      ],
      showUserNoList: [],
      TextAreaVisible: false,
      pdfConfig: {},
      modalVisible: false,
      numPages: null,
      fileUrl: '',
      pdfVisible: false
    }
  },
  computed: {
    ...mapGetters({
      project: 'project'
    }),
    projectClosed () {
      return this.project?.status === 3
    }
  },
  created () {
    const pd = localStorage.getItem('CURRENT_PROID')
    if (pd) {
      this.queryParam.proId = parseInt(pd)
    }
    this.configId = this.$route.query.configId
  },
  mounted () {
    // this.getshowUserNo()
  },
  methods: {
    // 查看合同模板
    clickViewFile (fileUrl) {
      const url = this.$options.filters.dealImageUrl(fileUrl)
      // this.modalVisible = true
      // const loadingTask = pdf.createLoadingTask(url)
      // loadingTask.promise.then(pdf => {
      //   this.numPages = pdf.numPages
      //   this.initPage()
      // }).catch(err => {
      //   console.error('pdf 加载失败', err)
      //   this.initPage()
      // })
      this.pdfVisible = true
      this.fileUrl = url
    },
    initPage () {
      this.$nextTick(() => {
        window.scrollTo(0, 0)
      }, 200)
    },
    // 查看文件
    viewFile (row) {
      this.viewFileVisible = true
      this.$nextTick(() => {
        this.$refs.viewFileRef.handleData(row)
        this.$forceUpdate()
      })
    },
    closeViewFile () {
      this.viewFileVisible = false
    },
    cancelContract ({ id, proId }) {
      this.$confirm({
        title: this.$t('all.autotext730'),
        content: this.$t('all.autotext834'),
        okText: this.$t('all.autotext792'),
        cancelText: this.$t('all.autotext975'),
        onOk: () => {
          const params = {
            id,
            proId,
            configId: this.configId
          }
          return apiCancelContract(params).then(() => {
            this.$message.success(this.$t('all.autotext770'))
            this.$refs.table.refresh(true)
          })
        }
      })
    },
    // 请求下拉框
    // getshowUserNo () {
    //   showUserNo({ proId: this.queryParam.proId, configId: this.configId })
    //     .then(res => {
    //       console.log('下拉框', res)
    //       this.showUserNoList = res
    //     })
    //     .catch(() => {})
    // },
    // 发起合同
    initiate () {
      this.visible = true
      this.$refs.ContractDisplay.getTemplate()
      // alert(123)
    },
    // 上传
    upload () {
      this.visibleUpload = true
    },
    visibleDeploySwitch (record) {
      this.visibleDeploy = true
      this.currentTemplateRow = { ...record }
      this.contractId = record.id
    },
    switchState (record, val) {
      if (record.signConfig || !val) {
        this.toggleStatus()
        switchUpdateCon({
          id: record.id,
          name: record.name,
          configId: this.configId
        }).then((res) => {
          console.log(res)
          this.$refs.tables.refresh(true)
        })
      } else {
        this.$message.error(this.$t('all.autotext245'))
      }
    },
    checkProject () {
    },
    // 查询事件
    activeQuery (value) {
      if (value === 'reset') {
        this.queryParam = {
          proId: this.queryParam.proId,
          configId: this.configId
        }
        this.$refs.table.refresh(true)
      } else {
        this.loadData(this.queryParam)
        this.$refs.table.refresh(true)
      }
    },
    // 弹窗确认
    addSubmit (form) {
      console.log(form)
      this.$refs.ContractDisplay.submitting = true
      getAddContract({
        ...form,
        configId: this.configId
      })
        .then((res) => {
          this.$refs.ContractDisplay.submitting = false
          this.$refs.ContractDisplay.form = {}
          this.$refs.ContractDisplay.sysAdmins = ''
          this.$refs.ContractDisplay.reId = ''
          this.$refs.ContractDisplay.selectedGroud = null
          this.$refs.ContractDisplay.expandedRowKeys = []
          this.$refs.ContractDisplay.selectedRowKeys = []
          this.$refs.ContractDisplay.selectedNumber = 0
          this.$message.success(this.$t('all.autotext470'))
          this.visible = false
          this.$refs.ContractDisplay.confirmLoading = false
          this.$refs.table.refresh(true)
          console.log(res)
        })
        .catch(() => {
          this.$refs.ContractDisplay.confirmLoading = false
        })
    },
    // 弹窗取消
    addCancel () {
      this.visible = false
      this.$refs.ContractDisplay.submitting = false
      this.$refs.ContractDisplay.form = {}
      this.$refs.ContractDisplay.sysAdmins = ''
      this.$refs.ContractDisplay.reId = ''
      this.$refs.ContractDisplay.expandedRowKeys = []
      this.$refs.ContractDisplay.selectedRowKeys = []
      this.$refs.ContractDisplay.selectedGroud = null
      this.$refs.ContractDisplay.selectedNumber = 0
    },
    // 弹窗二确认
    AllocationOk (signConfig) {
      if (signConfig.length === 0) {
        this.$message.warning(this.$t('all.autotext493'))
        return
      }
      this.$refs.Allocation.submitting = true
      contractConfig({ id: this.contractId, signConfig: JSON.stringify(signConfig), configId: this.configId })
        .then((res) => {
          this.$refs.Allocation.submitting = false
          this.$message.success(this.$t('all.autotext470'))
          this.$refs.tables.refresh(true)
          this.visibleDeploy = false
          this.$refs.Allocation.clearData()
          console.log(res)
        })
        .catch(() => {
          this.$refs.Allocation.submitting = false
        })
    },
    // 弹窗二取消
    AllocationCancel () {
      this.visibleDeploy = false
      this.currentTemplateRow = {}
    },
    uploadModalCancel () {
      this.visibleUpload = false
      this.$refs.UploadContract.resetForm()
    },
    uploadClickConfirm (value) {
      const test = this.queryParam.proId
      this.$refs.UploadContract.submitting = true
      getAddCon({ ...value, proId: test, configId: this.configId })
        .then((res) => {
          this.$refs.UploadContract.submitting = false
          this.$message.success(this.$t('all.autotext470'))
          this.$refs.tables.refresh(true)
          this.visibleUpload = false
          this.$refs.UploadContract.resetForm()
        })
        .catch(() => {
          this.$refs.UploadContract.submitting = false
          this.$message.success(this.$t('all.autotext69'))
        })
    },
    // 导出合同
    clickExport () {
      const commitData = { proId: this.queryParam.proId, status: this.queryParam.status, configId: this.configId }
      exportContract(commitData)
        .then(res => {
          exportExcel(this.$t('all.autotext1257'), res)
        })
        .catch(() => {})
    },
    // 合同模板停用/启用转换埋点
    toggleStatus () {},
    handleTextAreaCancel () {
      this.TextAreaVisible = false
    },
    handleTextAreaSuccess () {
      this.TextAreaVisible = false
      this.$refs.tables.refresh(true)
    },
    openTextArea (record) {
      this.pdfConfig = { ...record }
      this.TextAreaVisible = true
    }
  }
}
</script>
<style scoped lang="scss"></style>
